package tech.horgee.aoptest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Objects;

@Service
@Aspect
public class LimitAspect {
    @Autowired
    RedisTemplate redisTemplate;

    @Around("@annotation(tech.horgee.aoptest.Limit)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("方法调用前");
        // 获取请求参数
        Object[] args = joinPoint.getArgs();
        // 获取错误次数
        int count = 0;
        if (Objects.nonNull(args[0])) {
            Object o = redisTemplate.opsForValue().get("LoginCount::" + args[0]);
            if (Objects.nonNull(o)) {
                count = (Integer) o;
            }
        }
        if (count > 2) {
            return MyCode.TOO_MANY.toResult();
        }
        // 目标方法调用
        return joinPoint.proceed();
    }

    @AfterThrowing("@annotation(tech.horgee.aoptest.Limit)")
    public void throwing(JoinPoint joinPoint) {
        // 获取请求参数
        Object[] args = joinPoint.getArgs();
        // 获取错误次数
        int count = 0;
        if (Objects.nonNull(args[0])) {
            Object o = redisTemplate.opsForValue().get("LoginCount::" + args[0]);
            if (Objects.nonNull(o)) {
                count = (Integer) o;
            }
        }
        redisTemplate.opsForValue().set("LoginCount::" + args[0], ++count, Duration.ofMinutes(1));
    }
}
